package com.meihua.baoleyi.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.meihua.baoleyi.R;
import com.meihua.baoleyi.base.BaseActivity;
import com.meihua.baoleyi.common.MyApp;
import com.meihua.baoleyi.common.PrefsHelper;
import com.meihua.baoleyi.net.NetHelper;
import com.meihua.baoleyi.utils.CountDownTimerUtils;
import com.meihua.baoleyi.utils.MD5;
import com.meihua.baoleyi.utils.ToastUtils;
import com.meihua.baoleyi.utils.UrlContants;
import com.meihua.baoleyi.utils.ValidateHelper;

import org.json.JSONException;

import java.util.TreeMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by liming on 2017/10/24.
 * 重置手机号
 */

public class ResetPhoneActivity extends BaseActivity  {

    @Bind(R.id.text_back)
    ImageView back;
    @Bind(R.id.text_title)
    TextView tv_title;
    @Bind(R.id.et_phone)
    EditText et_phont;
    @Bind(R.id.et_password)
    EditText et_password;
    @Bind(R.id.bt_verify)
    TextView bt_verify;
    private String phone,user_id,newphone,phoneNum;
    @Bind(R.id.tv_phone)
    TextView tv_phone;
    @Bind(R.id.tv_password)
    TextView tv_password;
    @Bind(R.id.get_code)
    Button get_code;
    String userid;

    /**
     * 创建跳转Intent
     */
    public static Intent createIntent(Context mContext) {
        Intent intent = new Intent(mContext, ResetPhoneActivity.class);
        return intent;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reset_phone);
        ButterKnife.bind(this);
        initView();
    }

    /**
     * 初始化
     */
    private void initView() {
        tv_title.setText("重置手机号码");
        phone = getIntent().getStringExtra("phone");
        bt_verify.setOnClickListener(this);
        back.setOnClickListener(this);
        get_code.setOnClickListener(this);
        et_phont.addTextChangedListener(new MyTextWatcher());
    }

    /**
     * 点击事件
     * @param v
     */
    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.bt_verify:
                if (et_password.getText().toString().equals("")){
                    Toast.makeText(ResetPhoneActivity.this,"请输入密码",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (et_phont.getText().toString().equals("")){
                    Toast.makeText(ResetPhoneActivity.this,"请输入电话号码",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (bt_verify.getText().toString().equals("验证")&& tv_phone.getText().toString().equals("输入旧手机号:")){
                    getverify();  //验证旧手机号
                }else if (bt_verify.getText().toString().equals("下一步")){
                    getnextstep();
                }else if (bt_verify.getText().toString().equals("验证") && tv_phone.getText().toString().equals("新手机号:")){
                 getnewphone();//验证新手机号
                }
                break;
            case R.id.text_back: //返回
                finish();
                break;
            case R.id.get_code:
                sendSmsCode();
                break;
        }
    }
    /**
     *  验证新手机号
     */
    private void getnewphone() {
        if (et_password.getText().toString().trim().equals("")){
            Toast.makeText(ResetPhoneActivity.this,"请输入验证码",Toast.LENGTH_SHORT).show();
            return;
        }
        showDialog();
        TreeMap<String, String> treeMap = new TreeMap<String, String>()
        {
            {
                put("user_id", userid);
                put("new_phone", phoneNum);
                put("code", et_password.getText().toString().trim());
            }
        };
        NetHelper.post(UrlContants.VERITY_NEWPHONE, treeMap, true, new NetHelper.HttpCallBack() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (s != null) {
                    JSONObject jsonob = JSONObject.parseObject(s);
                    String code = jsonob.getString("code");
                    String msg = jsonob.getString("msg");
                    if (code.equals("200")){
                        MyApp.getInstance().exit();
                        myApp.logout(); //退出成功后清除用户有关的信息
                        PrefsHelper.removeLoginInfo(); //清除保存的登入信息
                        startActivity(new Intent(ResetPhoneActivity.this, LoginActivity.class));
                    }else {
                        Toast.makeText(ResetPhoneActivity.this,msg,Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Toast.makeText(ResetPhoneActivity.this,"数据为空",Toast.LENGTH_SHORT).show();
                }
                dismissDialog();
            }
        });

    }
    public boolean isEmpty(String str) {
        return str == null || "".equals(str.trim()) || "null".equals(str);
    }
     //发送验证码
    private void sendSmsCode() {
        if (isEmpty(et_phont.getText().toString().trim())) {
            showShortCenter(this, R.string.input_phone);
            return;
        }
        CountDownTimerUtils countDownTimerUtils = new CountDownTimerUtils(ResetPhoneActivity.this, get_code, 60000, 1000);
        countDownTimerUtils.start();
        phoneNum = et_phont.getText().toString().trim();
        boolean result = ValidateHelper.isPhoneNumberValid(phoneNum);
        if (!result) {
            Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
            return;
        }

        long time=System.currentTimeMillis()/1000;//获取系统时间的10位的时间戳
        String str=String.valueOf(time);
        String token=myApp.getToken().toString();
        String sign_none="phone="+phoneNum + ""+"&timestamp="+str+"&token="+token;
        String sign_yes = MD5.getMessageDigest(sign_none.toString().getBytes()).toUpperCase();

        OkGo.get(UrlContants.RESERT_PHONE_SEND_CODE+"?phone="+phoneNum + ""+"&timestamp="+str+"&token="+token+"&sign="+sign_yes)
                .tag(this)
                .params("phone", phoneNum)
                .params("timestamp",str)//时间戳
                .params("token",token)//token
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (s != null) {
                            try {
                                org.json.JSONObject jsonObject = new org.json.JSONObject(s);
                                if (jsonObject.optString("code").equals("200")) {
                                    ToastUtils.showT(ResetPhoneActivity.this, "发送验证码成功！");
                                } else {
                                    String message = jsonObject.getString("msg");
                                    ToastUtils.showT(ResetPhoneActivity.this, message);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                    }
                });
    }
    private static Toast toast;
    public static void showShortCenter(Context context, int content) {
        if (toast == null) {
            toast = Toast.makeText(context, content, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
        } else {
            toast.setText(content);
            toast.setGravity(Gravity.CENTER, 0, 0);
        }
        toast.show();
    }
    private void getnextstep() {
        tv_password.setVisibility(View.GONE);
        et_password.setHint("请输入手机短信中的验证码");
        tv_phone.setText("新手机号:");
        et_phont.setText("");
        et_password.setText("");
        get_code.setVisibility(View.VISIBLE);
        bt_verify.setText("验证");
        bt_verify.setBackgroundResource(R.drawable.bg_round_green);
    }
    //验证旧手机号
    private void getverify() {
        showDialog();
        userid =myApp.getUser_id() ;
        TreeMap<String, String> treeMap = new TreeMap<String, String>()
        {
            {
                put("user_id", userid);
                put("old_phone", realStr);
                put("password", et_password.getText().toString().trim());
            }
        };
        NetHelper.post(UrlContants.VERITY_OLDPHONE, treeMap, true, new NetHelper.HttpCallBack() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (s != null) {
                    JSONObject jsonob = JSONObject.parseObject(s);
                    String code = jsonob.getString("code");
                    String msg = jsonob.getString("msg");
                    String phone = jsonob.getString("phone");
                    if (code.equals("200")){
                        Toast.makeText(ResetPhoneActivity.this,msg,Toast.LENGTH_SHORT).show();
                        bt_verify.setText("下一步");
                        newphone = phone;
                    }else {
                        Toast.makeText(ResetPhoneActivity.this,msg,Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Toast.makeText(ResetPhoneActivity.this,"数据为空",Toast.LENGTH_SHORT).show();
                }
                dismissDialog();
            }
        });

    }
    /**
     * 存储真实的字符
     * 比如提交后台
     */
    private String realStr = "";
    /**
     * 添加对editview的监听
     */
    class MyTextWatcher implements TextWatcher {
        private String displayStr = "";//显示在editext上的字符串

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if(s.toString().trim().equals(displayStr.trim())){//这个判断一定要写不然要陷入死循环
                // （et.setText会触发onTextChanged我又在onTextChanged里使用了setText方法）
                return;
            }
            if(before > 0){
                String delStr = realStr.substring(start, start+before);
                String result = realStr.substring(0, start)+realStr.substring(start+before);
                realStr = result;
            }
            if(count>0){
                CharSequence tmp = s.subSequence(start, start+count);
                StringBuilder sb = new StringBuilder(realStr);
                sb.insert(start, tmp);
                realStr = sb.toString();
                //realStr += tmp;
            }

            displayStr = getDisplayStr(realStr);
            String old = et_phont.getText().toString().trim();
//            et_phont.setText(displayStr);
//            et_phont.setSelection(displayStr.length());
        }
        /**
         获取用于显示的带星花的字符，不提交后台
         */
        private String getDisplayStr(String realStr) {
            String result = new String(realStr);
            char[] cs = result.toCharArray();
            for(int i = 0;i < cs.length;i++){
                if(i >= 3&& i <= 6){//把3和10区间的字符隐藏
                    cs[i] = '*';
                }
            }
            return new String(cs);
        }
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }
}
